/*
 *    Copyright (C) 2011-2012 Hai Bison
 *
 *    See the file LICENSE at the root directory of this project for copying
 *    permission.
 */

package group.pals.mailgate.utils;

import group.pals.mailgate.preferences.PreferencesAdapter;
import group.pals.mailgate.preferences.Preferences;
import group.pals.utils.net.Proxy;
import java.util.Date;

/**
 *
 * @author Hai Bison
 */
public final class Initialization {

    private final Preferences _Preferences;

    private Initialization() {
        this._Preferences = Preferences.getInstance();
        this._Preferences.addPreferencesListener(new PreferencesAdapter() {

            @Override
            public void preferencesStored() {
                initNetwork();
            }
        });

        initSecurityModule();
        initNetwork();
    }

    public static Initialization getInstance() {
        return InitializationHolder.INSTANCE;
    }

    private static class InitializationHolder {

        private static final Initialization INSTANCE = new Initialization();
    }

    /*----------------------------------------------------------------------------
     * STATIC VALUES
     */
    public static final Date StartTime = new Date();

    /*----------------------------------------------------------------------------
     * IMPLEMENTATION
     */
    public void initSecurityModule() {
        //configure the JVM to use the JSSE security.
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
//    java.security.Security.setProperty("ssl.SocketFactory.provider",
//            "group.pals.mailgate.utils.DummySSLSocketFactory");
    }

    public void initNetwork() {
        final String SocksProxyHost = "socksProxyHost";
        final String SocksProxyPort = "socksProxyPort";
        final String SocksProxyUsername = "java.net.socks.username";
        final String SocksProxyPassword = "java.net.socks.password";

        if (_Preferences.isUseSOCKSProxy()) {
            Proxy proxy = _Preferences.getSOCKSProxy();
            System.setProperty(SocksProxyHost, proxy.getAddress());
            System.setProperty(SocksProxyPort, Integer.toString(proxy.getPort()));
            System.setProperty(SocksProxyUsername, proxy.getUsername());
            System.setProperty(SocksProxyPassword, proxy.getPassword());
        } else {
            System.clearProperty(SocksProxyHost);
            System.clearProperty(SocksProxyPort);
            System.clearProperty(SocksProxyUsername);
            System.clearProperty(SocksProxyPassword);
        }
    }
}
